package com.wswy.wzcx.ui.card

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import com.blankj.utilcode.util.SizeUtils
import com.wswy.wzcx.AppContext
import com.wswy.wzcx.R
import com.wswy.wzcx.model.license.VehicleLicenseModel
import com.wswy.wzcx.module.UserDataProvider
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.base.addDividerLine
import com.wswy.wzcx.utils.ResUtils
import kotlinx.android.synthetic.main.fragment_my_license.*


/**
 * 我的证件
 */
class MyLicenseFragment : CBaseFragment() {

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_my_license
    }

    override fun getFragmentTitle(): String {
        return AppContext.getContext().getString(R.string.my_license)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        rv_vehicle_layouts.layoutManager = LinearLayoutManager(requireContext())

        rv_vehicle_layouts.addDividerLine()
        val adapter = LicenseCardAdapter()

        rv_vehicle_layouts.adapter = adapter


        UserDataProvider.get().myCars()?.subscribe { t1, t2 ->

            t1?.orNull()?.apply {

                //addAll(this)

            }?.map { VehicleLicenseModel(carNo = it.carNo) }?.let {list ->


                adapter.datas.addAll(list)
                adapter.datas.add("dsfdsf")

                adapter.notifyDataSetChanged()

            }

        }

//        val list = arrayListOf(VehicleLicenseModel(carNo = "沪A"),
//                VehicleLicenseModel(),
//                VehicleLicenseModel(),
//                VehicleLicenseModel(),
//                VehicleLicenseModel())
//
//       showVehicles(true,list)

//        val transition = LayoutTransition()
        //transition.enableTransitionType(LayoutTransition.CHANGING)

//        val appearAnim = ObjectAnimator
//                .ofFloat(null as View?, "rotationY", 90f, 0f)
//                .setDuration(transition.getDuration(LayoutTransition.APPEARING))
//        transition.setAnimator(LayoutTransition.APPEARING, appearAnim)
//
//        //使用翻转消失的动画代替默认动画
//        val disappearAnim = ObjectAnimator.ofFloat(null as View?, View.ROTATION_X, 0f,
//                90f).setDuration(
//                transition.getDuration(LayoutTransition.DISAPPEARING))
//        transition.setAnimator(LayoutTransition.DISAPPEARING, disappearAnim)

        //使用滑动动画代替默认布局改变的动画
        //这个动画会让视图滑动进入并短暂地缩小一半，具有平滑和缩放的效果
//        val pvhSlide = PropertyValuesHolder.ofFloat("y", 0f, 1f)
//        val pvhScaleY = PropertyValuesHolder.ofFloat("scaleY",
//                1f, 0.5f, 1f)
//        val pvhScaleX = PropertyValuesHolder.ofFloat("scaleX",
//                1f, 0.5f, 1f)
//
//        //这里将上面三个动画综合
//        val changingDisappearAnim = ObjectAnimator.ofPropertyValuesHolder(
//                null as View?, pvhSlide)
//        changingDisappearAnim.duration = transition.getDuration(LayoutTransition.CHANGE_DISAPPEARING)
//        transition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING,
//                changingDisappearAnim)


//        ll_vehicle_layouts.layoutTransition = transition
    }

//    private val clickShowMoreVehicles = View.OnClickListener {
//        (it.getTag(R.id.item_data) as? List<VehicleLicenseModel>)?.let {
//            showVehicles(false,it)
//        }
//
//    }
//
//    private fun showVehicles(showMore: Boolean, list: List<VehicleLicenseModel>?,readerMore:Boolean = false) {
//        //添加证件
//        var from = 0
//        var end = 0
//
//        val len = list?.size?:0
//
//        val container = ll_vehicle_layouts
//        val context = container.context
//        val spaceH = SizeUtils.dp2px(21f)
//
//        tv_vehicle_count.text = getString(R.string.license_all,len)
//
//
//        if (showMore) {
//            container.removeAllViewsInLayout()
//            from = 0
//            end = minOf(2, len)
//        } else {
//            from = 2
//            end = len
//
//            container.getChildAt(container.childCount-1)?.let {
//
//                //删除
//                container.removeView(it)
//                container.addView(LicenseDView(context),LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,spaceH))
//            }
//
//        }
//
//        if(from >= end){
//            return
//        }
//
//
//        val more = showMore && len > end
//
//        for (i in from until end){
//
//            //添加卡片内容
//            container.addView(LicenseCardLayout(context).apply {
//                list?.get(i)?.let {
//                    bindData(it){
//
//                        val idx =container.indexOfChild(it)
//                        if (idx >=0){
//
//                            //删除线条
//                            (container.getChildAt(idx+1) as? LicenseDView)?.let {
//                                container.removeViewAt(idx+1)
//                            }
//                            //删除卡片
//                            container.removeView(it)
//
//                            //删除数据
//                            list.toMutableList().run {
//
//                                //刷新
//                                removeAt(i)
//
//                                //刷新
//                                //showVehicles(first, this)
//                            }
//                        }
//                    }
//                }
//            }, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT))
//
//            if (i != end - 1) {
//                //添加分割线
//                container.addView(LicenseDView(context), LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, spaceH))
//            } else if (more && i == end - 1) {
//
//                //添加
//                LinearLayout(context).apply {
//                    id = R.id.ll_layout_msg
//
//                    orientation = LinearLayout.VERTICAL
//
//                    addView(LicenseDView(context), LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(1f)))
//                    addView(TextView(context).apply {
//
//                        gravity = Gravity.CENTER
//                        textSize = 12f
//                        setTextColor(ContextCompat.getColor(context, R.color.colorPrimary))
//                        setBackgroundResource(ResUtils.getSelectableItemBackground(context))
//                        text = getString(R.string.expand_all_vehicle_license)
//
//                    }, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(40f)))
//
//                }.let {
//
//                    it.setTag(R.id.item_data, list)
//                    it.setOnClickListener(clickShowMoreVehicles)
//                    container.addView(it, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
//                }
//
//            }
//        }
//
//    }


    private class LicenseDView: View{

        constructor(context: Context) : this(context, null)

        constructor(context: Context, attribute: AttributeSet?) : this(context, attribute, 0)

        constructor(context: Context, attribute: AttributeSet?, defStyle: Int) : super(context, attribute, defStyle) {
        }

        private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
            color = Color.parseColor("#1a000000")
            style = Paint.Style.FILL
        }

        private val rect = Rect()

        override fun onDraw(canvas: Canvas?) {
            super.onDraw(canvas)

            rect.set(0,0,width,SizeUtils.dp2px(1f))
            canvas?.drawRect(rect,paint)
        }

    }





    private class LicenseCardAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>(),View.OnClickListener{


        val datas = ArrayList<Any>()

        companion object {
            private const val TYPE_ITEM_CARD = 1
            private const val TYPE_TYPE_MORE = 2
        }

        override fun getItemViewType(position: Int): Int {
            return when(datas[position]){
                is VehicleLicenseModel -> TYPE_ITEM_CARD
                else -> TYPE_TYPE_MORE
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return when(viewType){
                TYPE_ITEM_CARD -> {
                    LicenseCardViewHolder(LicenseCardLayout(parent.context))
                }
                TYPE_TYPE_MORE -> {
                    MoreCardViewHolder(LinearLayout(parent.context).apply {
                        orientation = LinearLayout.VERTICAL
                        addView(LicenseDView(context), LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(1f)))
                        addView(TextView(context).apply {
                            gravity = Gravity.CENTER
                            textSize = 12f
                            setTextColor(ContextCompat.getColor(context, R.color.colorPrimary))
                            setBackgroundResource(ResUtils.getSelectableItemBackground(context))
                            text = "查看更多"
                        }, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(40f)))

                    })
                }
                else -> object:RecyclerView.ViewHolder(View(parent.context)){}
            }
        }

        override fun getItemCount(): Int {
            return datas.size
        }

        override fun onClick(v: View?) {
            if (v?.id == R.id.tv_delete){
                //删除
                (v.getTag(R.id.item_data) as? RecyclerView.ViewHolder)?.let {
                    datas.removeAt(it.adapterPosition)
                    notifyItemRemoved(it.adapterPosition)

                    //删除更多按钮
                    if (datas.size <=3 && datas.isNotEmpty()){
                        if (datas.last() !is VehicleLicenseModel){
                            datas.removeAt(datas.size-1)

                            notifyItemRemoved(datas.size-1)
                        }
                    }

                }

            }
        }

        override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
            when(viewHolder){
                is LicenseCardViewHolder -> {

                    viewHolder.cardLayout.bindData(datas[position] as? VehicleLicenseModel)
                    viewHolder.cardLayout.deleteView().let {
                        it.setTag(R.id.item_data,viewHolder)
                        it.setOnClickListener(this)
                    }

                }

                is MoreCardViewHolder -> {

                }
            }
        }

    }


    private class LicenseCardViewHolder(val cardLayout:LicenseCardLayout) : RecyclerView.ViewHolder(cardLayout){

    }

    private class MoreCardViewHolder(itemView:View) : RecyclerView.ViewHolder(itemView){

    }

}